'use strict'
const path = require('path')
const http = require('http')
const fs = require('fs')
const handlebars = require('handlebars')
const promisify = require('util').promisify

const conf = require('./cps_config.js')
const cps = require('./cps.js')
const debug = require('./debug.js')
const dll = require('../lw/lw.js')
const lw = dll('../lw/test11.dll')

const server = http.createServer((req, res) => {
  const tar = path.join(conf.root, req.url)
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.write('\n')
  res.write('当前的url是:' + req.url + '\n')

  fs.stat(tar, (err, stats) => {
    if (err) {
      res.statusCode = 404;
      res.setHeader('Content-Type', 'text/plain');
      res.write(req.url + ' tar is not exist.')
      res.end()
      return

    } else if (stats.isFile()) {
      res.write('tar is file')
      res.end()
      return

    } else if (stats.isDirectory()) {
      fs.readdir(tar, (err, fl) => {

        fl.forEach(function(element, index) {
          res.write(element)
          res.write('\n')
        });
        res.end()
        return
      })
    }

  })
});

/*开始监听*/
server.listen(conf.port, conf.hostname, function() {
  let addr = `当前hostname:${conf.hostname},端口:${conf.port}`
  console.info(`服务器已启动:${addr} 随机验证:${lw.random(99,999)}`)
})